package com.lychee.binderdemo;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private IBinder mReporterBind;
    private Intent intentService;
    private BindConnection conn;

    private class BindConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mReporterBind = service;

            Parcel data = Parcel.obtain();
            Parcel reply = Parcel.obtain();
            data.writeInterfaceToken("reporter");
            data.writeString("我是客户端传给Service的字符串");

//            User user = new User("Hejingzhou","1230");
//            Bundle bundle = new Bundle();
//            bundle.putParcelable("userdata",user);
//            data.writeBundle(bundle);

            data.writeInt(1);
            try {
                mReporterBind.transact(BinderService.REPORT_CODE, data, reply, 0);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            reply.enforceInterface("reporter");
            int result = reply.readInt();
            System.out.println("这是Service端处理完的数据进行处理\t" + result);
            data.recycle();
            reply.recycle();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mReporterBind = null;
            System.out.println("连接断开");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intentService = new Intent(this, BinderService.class);
        conn = new BindConnection();
        boolean b = bindService(intentService, conn, BIND_AUTO_CREATE);
        System.out.println(b ? "连接成功------" : "连接失败-----");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
        stopService(intentService);
        conn = null;
        intentService = null;
    }
}
